package chances.wechat.api;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Observable;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import chances.wechat.WechatException;
import chances.wechat.service.WechatTokenService;

//@Service("tokenFactory")
//@EnableScheduling
public class TokenFactory extends Observable implements Serializable {
	
	private static final long serialVersionUID = -5506957350110623176L;

	private static Map<String, TokenSet> tokenMap = new HashMap<String, TokenSet>();
	
	@Autowired
	WechatTokenService tokenService;
	
	@Value("${wechat.token.flag}")
	private int tokenFlag = 0; // token获取标示，0从数据库获取值，1从微信获取值
	
	@Value("${wechat.token.refresh.time:0}")
	private int tokenRefreshTime;
	
//	@PostConstruct
//	public void init() {
//		reLoad();
//		checkToken();
//	}
//
//	private void reLoad() {
//		List<TokenSet> tokenSets = tokenService.getAllWechatToken();
//		for (TokenSet token : tokenSets) {
//			tokenMap.put(token.getAppCode(), token);
//		}
//	}
//	
//	@Scheduled(fixedDelay = 60000)
//	public void checkToken() {
//		Thread thread = new Thread(new Runnable() {
//			@Override
//			public void run() {
//				if(tokenFlag == 1) {
//					for (TokenSet token : tokenMap.values()) {
//						if(token.isAccessTokenRefresh(tokenRefreshTime)) {
//							TokenRefresh tokenRefresh = new TokenRefresh(token);
//							tokenRefresh.run();
//							tokenService.saveWechatToken(token);
//						}
//						
//					}
//				} else {
//					reLoad();
//				}
//				
//			}
//		});
//		thread.start();
//		
//	}

	public int getTokenFlag() {
		return tokenFlag;
	}

	public void setTokenFlag(int tokenFlag) {
		this.tokenFlag = tokenFlag;
	}
	
	public String getAccessToken(String appCode) {
		TokenSet tokenSet = tokenMap.get(appCode);
		if(tokenSet != null) {
			return tokenSet.getAccessToken();
		} else {
			throw new WechatException("appCode:" + appCode + ", no token.");
		}
		
	}
	
	public String getJsApiTicket(String appCode) {
		TokenSet tokenSet = tokenMap.get(appCode);
		if(tokenSet != null) {
			return tokenSet.getJsApiTicket();
		} else {
			throw new WechatException("appCode:" + appCode + ", no jsTicket.");
		}
		
	}
	
	public TokenSet getTokenSet(String appCode) {
		TokenSet tokenSet = tokenMap.get(appCode);
		if(tokenSet != null) {
			return tokenSet;
		} else {
			throw new WechatException("appCode:" + appCode + ", no tokenSet.");
		}
		
	}
	
}
